import { defineStore } from "pinia";
import { LoginData, Result, userInfo } from "@/types/types.ts";
import { doLogin } from "@/api/hosiptal";
import router from "@/router";

const useUserStore = defineStore("User", {
  state: () => {
    return {
      // 对话框显示隐藏
      dialogFormVisible: false,
      name: "",
      age: 0,
      sex: "",
      userInfo:
        JSON.parse(localStorage.getItem("userInfo") as string) ||
        ({} as userInfo),
    };
  },
  actions: {
    checkLogin() {
      // 判断是否需要登录...
      this.dialogFormVisible = true;
      return;
    },
    async login(loginData: LoginData) {
      // 登录...
      let result: Result = await doLogin(loginData);
      if (result.code === 200) {
        console.log("登录成功", result.data);
        localStorage.setItem("userInfo", JSON.stringify(result.data));
        this.userInfo = result.data;
        return "ok";
      }
      return Promise.reject(result.msg);
    },
    logout() {
      // 退出登录...
      localStorage.removeItem("userInfo");
      this.userInfo = {} as userInfo;
      router.push("/home");
    },
  },
});

export default useUserStore;
